const app = getApp();
var api = require('../../api.js');
var mta = require('../../mta_analysis.js');
const backgroundAudioManager = wx.getBackgroundAudioManager();//关于音频的定义
Page({

  /**
   * 页面的初始数据
   */
  data: {
    courseIntegral: 0,
    judgeIos: true,
    settlementOff: false,
    settlementOn: false,
    currentTime: 0,
    courseInfo: true,
    curr: '',
    cover_pic: '',
    newmoney: 0,
    course_newmoney: 0,
    use_integral: 0,
    judge: false,
    judgeT: false,
    chagneT: false,
    change: false,
    curr: false,   //当前打开的视频id
    userBought: {
      value: 'userBought',
    },
    friend: {
      value: 'friend',
    },
    show_attr_picker: false,
    show_attr: false,
    show: false,
    message: false,
    tab_userBought: "",
    tab_friend: "",
    userChecked: false,
    friendChecked: false,
    form: {
      number: 1,
    },
    tab_friend: '',
    tab_userBought: '',
    tab_video: "active",
    tab_audio: "",
    // 音频的信息
    audioExist: true,//判断后台是否传了音频数据
    audioOn: false,//判断是否正在播放
    sliderValue: 0,//slider的值
    audioId: "",
    audioCoverImgUrl: "",
    audioSrc: "",
    audioTitle: "",
    audioSinger: "",
    audioAllTime: "",
    audioNowTime: "",
    // 收藏
    isContact: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var page = this;

    wx.setStorageSync("section_id", options.section_id);
    wx.setStorageSync("lesson_id", options.lesson_id);

    mta.Page.init();

    let user_id = options.user_id;
    wx.setStorageSync("bindparent_id", user_id);
  },

  //tab切换
  tabSwitch: function (e) {
    var tab = e.currentTarget.dataset.tab;
    if (tab == "video") {
      this.setData({
        tab_video: "active",
        tab_audio: "",
      });
      this.audioPause();
    } else {
      this.setData({
        tab_video: "",
        tab_audio: "active",
      });
      this.videoContext.pause();
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (e) {
    this.videoContext = wx.createVideoContext('myVideo')
    // this.audioCtx = wx.createAudioContext('myAudio')
  },

  videoPlay(e) {
    this.setData({
      curr: true
    })
    this.videoContext.play()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var page = this;

    var section_id = wx.getStorageSync('section_id');
    var lesson_id = wx.getStorageSync('lesson_id');
    var course_id = wx.getStorageSync('course_id');
    var access_token = wx.getStorageSync('access_token');
    var user_info = wx.getStorageSync('user_info');

    page.setData({
      section_id: section_id,
      lesson_id: lesson_id,
      course_id: course_id,
      access_token: access_token,
      user_info: user_info
    });

    page.getDetail();
    page.getOnlineDetail();
    page.getOfflineDetail();
    page.getInformation();

    wx.getNetworkType({
      success: function (res) {
        console.log(res)
        page.setData({
          networkType: res.networkType
        })
      }
    })

    var equipmentSystem = wx.getStorageSync('equipmentSystem');
    page.setData({
      equipmentSystem: equipmentSystem
    })
    console.log(page.data.equipmentSystem)

    page.judgeIos();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var url = app.getcurrentPageStr();
    wx.setStorageSync("from_url", url);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.bind();
    this.audioPause();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var page = this;

    page.getDetail();

    // 显示顶部刷新图标  
    wx.showNavigationBarLoading();

    // 隐藏导航栏加载框  
    wx.hideNavigationBarLoading();

    //停止下拉刷新
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var url = app.getcurrentPageStr();
    var user_id = wx.getStorageSync('user_id');
    console.log(url + "&user_id=" + user_id);
    return {
      path: url + "&user_id=" + user_id,
      title: '得道1314'
    };
  },

  //判断ios是否可以支付
  judgeIos: function () {
    var access_token = wx.getStorageSync('access_token');
    console.log(access_token)
    var page = this;
    wx.request({
      url: api.passport.is_ios,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token
      },

      success: function (res) {
        console.log(res);
        if (res.data.code == 1) {
          page.setData({
            judgeIos: false
          })
        }
      }


    });
  },

  //获取章节详情
  getDetail: function () {

    var page = this;
    var access_token = wx.getStorageSync('access_token');
    console.log(page.data.lesson_id);
    wx.request({
      url: api.index.sectionInfo,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        lesson_id: page.data.lesson_id,
        section_id: page.data.section_id
      },

      success: function (res) {
        console.log(res);


        if (res.data.code == 1) {

          wx.showModal({
            title: '提示',
            content: '您等级不够，请购买',
            cancelText: '暂不购买',
            confirmText: '立即购买',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定');
                wx.switchTab({
                  url: '../../pages/user/upgrade/upgrade',
                })
              } else if (res.cancel) {
                wx.switchTab({
                  url: '../../pages/index/index',
                })
              }
            }
          });

        } else if (res.data.code == 0) {

          console.log(3333333333)

          page.setData({
            name: res.data.data.info.name,
            // commentList: res.data.data.comment_list,
            detailList: res.data.data.section_info,
            info: res.data.data.info,
            course_id: res.data.data.section_info.course_id,
            is_buy: res.data.data.section_info.is_buy,
            course_buy: res.data.data.section_info.course_buy,
            videoSrc: res.data.data.section_info.video_info.PlayInfoList.PlayInfo[1].PlayURL,
            // 收藏
            isContact: res.data.data.section_info.is_collection,
          })

          // 下面放置音频所需要的信息
          console.log(res.data.data.section_info.audio_url);
          if (res.data.data.section_info.audio_url == '' || res.data.data.section_info.audio_url == null) {
            page.setData({
              audioExist: false,
            })
          } else {
            page.setData({
              audioId: res.data.data.info.id,
              audioCoverImgUrl: res.data.data.section_info.cover_pic,
              // audioSrc: res.data.data.section_info.video_info.PlayInfoList.PlayInfo[1].PlayURL,
              audioSrc: res.data.data.section_info.audio_url,
              audioTitle: res.data.data.section_info.video_info.VideoBase.Title,
              audioAllTime: res.data.data.section_info.video_info.VideoBase.Duration,
            })
          }

          wx.setNavigationBarTitle({
            title: page.data.name
          })
          page.getOfflineDetail();
          if (res.data.data.section_info.is_buy == true) {
            page.setData({
              judge: true,
              change: true,
              show: false
            })
          }

          if (res.data.data.section_info.course_buy == true) {
            page.setData({
              judgeT: true,
              changeT: true,
            })
          }

        } else if (res.data.code == -1) {
          console.log(44444444)
          wx.navigateTo({
            url: '/pages/grant/grant',
          })
        }

      }
    });
  },


  // 音频部分
  audio: function () {
    let that = this;
    backgroundAudioManager.autoplay = true
    backgroundAudioManager.title = that.data.audioTitle
    backgroundAudioManager.epname = that.data.audioSinger
    backgroundAudioManager.singer = that.data.audioSinger
    backgroundAudioManager.coverImgUrl = that.data.audioCoverImgUrl
    backgroundAudioManager.src = that.data.audioSrc
    backgroundAudioManager.onWaiting(() => {
      console.log("2、音频加载中");
    })
    backgroundAudioManager.onPlay(() => {
      console.log("1、音频开始播放");
      that.setData({
        audioOn: true,
      })
    })
    backgroundAudioManager.onPause(() => {
      console.log("6、音频暂停播放");
      that.setData({
        audioOn: false,
      })
    })
    backgroundAudioManager.onStop(() => {
      console.log("7、音频停止播放");
      that.setData({
        audioOn: false,
      })
    })
    backgroundAudioManager.onEnded((e) => {
      console.log("5、音频自然播放结束");
      that.setData({
        audioOn: false,
      })
    })
    backgroundAudioManager.onTimeUpdate(() => {
      console.log("4、音频播放进度更新");
      var value = (backgroundAudioManager.currentTime / backgroundAudioManager.duration) * 100;
      that.setData({
        sliderValue: value
      })
    })
    backgroundAudioManager.onError(() => {
      console.log("0、音频播放错误");
    })
    backgroundAudioManager.onCanplay(() => {
      console.log("3、音频进入可以播放状态");
    })
    backgroundAudioManager.onPrev(() => {
      console.log("prev、用户在系统音乐播放面板点击上一曲事件");
    })
    backgroundAudioManager.onNext(() => {
      console.log("next、用户在系统音乐播放面板点击下一曲事件");
    })
  },
  audioPlay: function (e) {
    var that = this;
    that.audio();
    backgroundAudioManager.play();
    backgroundAudioManager.autoplay = true
    backgroundAudioManager.title = that.data.audioTitle
    backgroundAudioManager.epname = that.data.audioSinger
    backgroundAudioManager.singer = that.data.audioSinger
    backgroundAudioManager.coverImgUrl = that.data.audioCoverImgUrl
    backgroundAudioManager.src = that.data.audioSrc
  },
  audioPause: function () {
    backgroundAudioManager.pause();
  },
  sliderchange: function (e) {
    var that = this;
    var allTime = that.data.audioAllTime;
    var time = e.detail.value;
    var stime = time / 100 * allTime;
    that.setData({
      audioNowTime: stime
    })
    backgroundAudioManager.play();
    backgroundAudioManager.seek(stime);
  },

  //写留言
  doMessage: function () {
    this.setData({
      show_attr: true,
      message: true,
      curr: true
    });
    var user_info = wx.getStorageSync('user_info');
    this.setData({
      nickName: user_info.nickName,
      comment: ''
    })
  },

  //获取留言内容
  realnameConfirm: function (e) {
    console.log(e)
    this.setData({
      comment: e.detail.value
    })
    console.log(this.data.comment)
  },

  //发布
  submit: function (e) {
    this.setData({
      show_attr: false,
      message: false,
      curr: false
    });
    var access_token = wx.getStorageSync('access_token');
    var user_id = wx.getStorageSync('user_id');
    var page = this;
    var comment = page.data.comment.replace(/\s/gi, '')

    if (!page.data.comment || comment.length == 0) {
      wx.showToast({
        title: '请填写内容',
        icon: 'none',
      });
    } else {
      wx.request({
        url: api.index.addComment,
        method: "post",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          access_token: access_token,
          section_id: page.data.section_id,
          user_id: user_id,
          comment: page.data.comment,
        },

        success: function (res) {
          console.log(res);
          var msg = res.data.msg;
          if (res.data.msg == '成功') {
            wx.showToast({
              title: msg,
              icon: 'none',
            });
            page.getDetail();
            page.getInformation()
          }
        }
      });
    }




  },

  // 获取留言信息
  getInformation: function () {
    var page = this;
    var access_token = wx.getStorageSync('access_token');
    console.log(access_token);
    wx.request({
      url: api.index.commentInfo,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        section_id: page.data.section_id,
        page: 1
      },

      success: function (res) {
        console.log(res)

        if (res.data.code == 0) {
          page.setData({
            commentList: res.data.list
          })
          console.log(page.data.commentList)

        } else if (res.data.code == -1) {
          wx.navigateTo({
            url: '/pages/grant/grant',
          })
        }

      }
    });
  },

  //点赞功能
  numAdd: function (res) {
    console.log(res)
    var page = this;
    var index = res.currentTarget.dataset.index;
    var commentsList = page.data.commentList;
    for (var i = 0; i < page.data.commentList.length; i++) {
      if (i == index) {
        // page.data.commentList[i].is_like = !page.data.commentList[i].is_like

        if (page.data.commentList[i].is_like == 1) {
          page.data.commentList[i].is_like = 0,
            page.data.commentList[i].applaud = parseInt(page.data.commentList[index].applaud) + 1
        } else {
          page.data.commentList[i].is_like = 1,
            page.data.commentList[i].applaud = parseInt(page.data.commentList[index].applaud) - 1
        }


      }

    }
    page.setData({
      commentList: page.data.commentList
    })

    var access_token = wx.getStorageSync('access_token');
    console.log(access_token);
    wx.request({
      url: api.index.like,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        comment_id: commentsList[index].id
      },

      success: function (res) {
        console.log(res)

        if (res.data.code == 0) {


        } else if (res.data.code == -1) {
          wx.navigateTo({
            url: '/pages/grant/grant',
          })
        }

      }
    });

  },

  //线上、线下切换
  tab: function (e) {

    var tab = e.currentTarget.dataset.tab;
    var equipmentSystem = wx.getStorageSync('equipmentSystem');
    if (tab == "online") {


      this.setData({
        equipmentSystem: equipmentSystem
      })
      console.log(this.data.equipmentSystem)
      if (this.data.is_buy == true) {
        this.setData({
          judge: true,
          change: true,
          show: false
        })
      } else {
        this.setData({
          tab_online: "active",
          tab_offline: "",
          show: true,
          change: false,
          show_attr_picker: false,
        })
      }
      this.getTotalMoney();
      console.log(this.data.change)

    } else {
      if (this.data.course_buy == true) {
        this.setData({
          judgeT: true,
          changeT: true,
        })
      } else {
        if (this.data.courseInfo == false) {
          wx.showToast({
            title: '该课程还未有线下课',
            icon: 'none',
          })
        } else {
          this.setData({
            tab_online: "",
            tab_offline: "active",
            show_attr_picker: true,
            show: false,
            changeT: false,
            curr: true,
          })
        }

      }
      this.getTotalMoneyOff();

    }
  },

  //线上课提交前预览页面
  getOnlineDetail: function () {
    var page = this;
    var access_token = wx.getStorageSync('access_token');
    wx.request({
      url: api.lessonOrder.submitPreview,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: page.data.lesson_id,
      },

      success: function (res) {
        console.log(res);

        if (res.data.code == 0) {
          page.setData({
            lessonInfo: res.data.data.lesson_info,
            user: res.data.data.user,
            money: res.data.data.user.integral2money,
            integral: res.data.data.user.integral,
            price: res.data.data.lesson_info.price
          })
          console.log(page.data.price)

        }

      }
    });
  },


  //线上开关选择器
  switchChange: function (e) {
    var page = this;
    console.log(e);
    page.setData({
      switchValue: e.detail.value
    })
    console.log(page.data.integral);

    if (page.data.switchValue == true) {
      page.setData({
        newmoney: page.data.money,
        use_integral: page.data.integral,
      })
    } else {
      page.setData({
        newmoney: 0,
        use_integral: 0
      })
    }
    page.getTotalMoney();
  },


  //线上获取总额
  getTotalMoney: function () {
    var page = this;
    var user_newmoney = page.data.newmoney;

    var price = page.data.price;
    console.log(user_newmoney)
    console.log(page.data.newmoney)
    var totalMoney = (parseFloat(price) * 100 - parseFloat(user_newmoney) * 100) / 100
    page.setData({
      totalMoney: totalMoney
    })
  },

  //线上结算
  settlementBtn: function () {
    var page = this;
    var access_token = wx.getStorageSync('access_token');
    page.getTotalMoney();
    console.log(page.data.use_integral)
    page.setData({
      settlementOn: true
    })
    wx.request({
      url: api.lessonOrder.submit,
      method: "post",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: page.data.lesson_id,
        num: 1,
        use_integral: page.data.use_integral,
      },

      success: function (res) {
        console.log(res);
        var data = res.data.data
        if (res.data.code == 0) {


          if (res.data.msg == "订单支付成功") {
            page.setData({
              judge: true,
              change: true,
            })
            console.log(4554654665465)
          } else {
            //发起支付
            wx.requestPayment({
              timeStamp: data.timeStamp,
              nonceStr: data.nonceStr,
              package: data.package,
              signType: data.signType,
              paySign: data.paySign,
              success: function (res) {
                console.log(res)
                page.setData({
                  judge: true,
                  change: true,
                })
                console.log(11111111111)
              },
              fail: function (res) {

              },
              complete: function (res) {

              }
            })
          }

        }

      }
    });
  },






  //线下提交前预览页面
  getOfflineDetail: function () {
    var page = this;
    var access_token = wx.getStorageSync('access_token');
    wx.request({
      url: api.courseOrder.submitPreview,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: page.data.course_id,
      },

      success: function (res) {
        console.log(res);

        if (res.data.code == 0) {

          if (res.data.data.course_info == null) {
            page.setData({
              changeT: true,
              judgeT: false,
              courseInfo: false
            })

          } else {
            page.setData({
              course_info: res.data.data.course_info,
              course_user: res.data.data.user,
              course_money: res.data.data.user.integral2money,
              course_integral: res.data.data.user.integral,
              course_price: res.data.data.course_info.price
            })
            console.log(page.data.course_money)
          }



        }

      }
    });
  },

  //数量相加
  numberSub: function () {
    var page = this;
    var num = page.data.form.number;
    if (num <= 1)
      return true;
    num--;
    page.setData({
      form: {
        number: num,
      }
    });
    page.getTotalMoneyOff();
  },
  //数量减少
  numberAdd: function () {
    var page = this;
    var num = page.data.form.number;
    num++;
    page.setData({
      form: {
        number: num,
      }
    });
    page.getTotalMoneyOff();
  },
  //改变输入框内的数量
  numberBlur: function (e) {
    var page = this;
    var num = e.detail.value;
    num = parseInt(num);
    if (isNaN(num))
      num = 1;
    if (num <= 0)
      num = 1;
    page.setData({
      form: {
        number: num,
      }
    });
    page.getTotalMoneyOff();
  },

  //线下开关选择器
  switchOff: function (e) {
    var page = this;
    console.log(e);
    page.setData({
      switchValue: e.detail.value
    })
    if (page.data.switchValue == true) {
      page.setData({
        course_newmoney: page.data.course_money,
        courseIntegral: page.data.course_integral,
      })
    } else {
      page.setData({
        course_newmoney: 0,
        courseIntegral: 0
      })
    }
    console.log(page.data.switchValue);
    console.log(page.data.courseIntegral);
    console.log(page.data.course_money);
    console.log(page.data.course_newmoney);
    page.getTotalMoneyOff();
  },


  //线下获取总额
  getTotalMoneyOff: function () {
    var page = this;
    var course_newmoney = page.data.course_newmoney;

    var course_price = page.data.course_price;
    var formNumber = page.data.form.number;
    var totalPrice = parseFloat(course_price) * parseFloat(formNumber)
    console.log(course_newmoney)
    console.log(course_price);
    console.log(totalPrice);
    var course_totalMoney = parseFloat(totalPrice) - parseFloat(course_newmoney);
    console.log(course_totalMoney)
    page.setData({
      course_totalMoney: course_totalMoney
    })
  },

  //线下结算
  settlementOffBtn: function () {
    var page = this;
    var access_token = wx.getStorageSync('access_token');
    console.log(page.data.course_id)

    console.log(page.data.course_totalMoney)



    page.setData({
      settlementOff: true
    })

    wx.request({
      url: api.courseOrder.submit,
      method: "post",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: page.data.course_id,
        num: page.data.form.number,
        use_integral: page.data.courseIntegral,
      },

      success: function (res) {
        console.log(res);
        var data = res.data.data
        if (res.data.code == 0) {

          if (res.data.msg == "订单支付成功") {
            page.setData({
              judgeT: true,
              changeT: true,
            })
            console.log(4554654665465)
          } else {
            //发起支付
            wx.requestPayment({
              timeStamp: data.timeStamp,
              nonceStr: data.nonceStr,
              package: data.package,
              signType: data.signType,
              paySign: data.paySign,
              success: function (res) {


                console.log(res)
                page.setData({
                  judgeT: true,
                  changeT: true,
                })


              },
              fail: function (res) {

              },
              complete: function (res) {

              }
            })
          }


        }

      }
    });
  },

  //点击弹窗退出
  clear: function () {
    var page = this;
    page.setData({
      show_attr: false,
      show_attr_picker: false,
      changeT: true,
      show: false,
      change: true,
      curr: false
    })
  },


  // 收藏与取消收藏
  collect: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    console.log(id);
    app.collect(id);
    that.setData({
      isContact: !that.data.isContact,
    })
  },

  //获取播放进度
  bindtimeupdate: function (res) {
    this.setData({
      currentTime: res.detail.currentTime
    })
  },

  //跳转到首页
  toIndex: function () {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }


})